<template>
  <div>
    <BasicTable @register="registerTable">
      <Alert message="Success Text" type="success" class="ml-4 mr-4" />
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'action'">
          <div class="flex justify-center">
            <TableAction :actions="tableActions(record)" />
          </div>
        </template>
      </template>
    </BasicTable>
  </div>
</template>
<script lang="ts" setup>
  import { BasicTable, useTable, TableAction, BasicColumn, FormSchema, ActionItem } from '@/components/Table';
  import {  apiTs } from '@/api/toolkit/apiTs';
  import { controllerList } from '@/api/toolkit/project';
  import { useMessage } from '@/hooks/web/useMessage';

  // 自定义组件名称, 默认为文件名
  defineOptions({ name: 'ApiTs' });

  // 表格—搜索
  const tableSearch: FormSchema[] = [
    {
      field: 'simpleName',
      label: '类名',
      component: 'Input',
      colProps: { span: 6 },
    },
    {
      field: 'moduleName',
      label: '模块',
      component: 'Input',
      colProps: { span: 6 },
    },

    {
      field: 'description',
      label: '描述',
      component: 'Input',
      colProps: { span: 6 },
    },
  ];

  // 表格-列
  const tableColumns: BasicColumn[] = [
    {
      title: '模块',
      dataIndex: 'moduleName',
      width: '5rem',
      align: 'center',
    },
    {
      title: '类名',
      dataIndex: 'simpleName',
      width: '10rem',
      align: 'left',
    },
    {
      title: '请求地址',
      dataIndex: 'requestUri',
      width: '20rem',
      align: 'left',
    },
    {
      title: '描述',
      dataIndex: 'description',
      width: '10rem',
      align: 'left',
    },
    {
      title: '操作',
      dataIndex: 'action',
      width: '5rem',
      align: 'left',
    },
  ];

  // 表格-按钮
  const tableActions = (record): ActionItem[] => [
    {
      icon: 'humbleicons:download',
      tooltip: `生成api.ts`,
      popConfirm: {
        title: '生成会覆盖现有代码',
        placement: 'top',
        confirm: handleGenApiTs.bind(null, record),
      },
    },
  ];

  // 表格
  const [registerTable, { reload }] = useTable({
    title: 'Controller 列表',
    api: controllerList,
    columns: tableColumns,
    // 搜索框配置: 是否打开搜索框、搜索框配置
    useSearchForm: true,
    formConfig: {
      labelWidth: 120,
      schemas: tableSearch,
      autoSubmitOnEnter: true,
    },
    // 表格配置:
    size: 'small', // 行高
    bordered: true, // 是否包含边框
    showIndexColumn: true, // 是否包含索引列
    titleHelpMessage: '根据服务端 Controller 自动生成前端调用的 api.ts 文件',
  });

  async function handleGenApiTs(record: Recordable) {
    await apiTs({ canonicalName: record.canonicalName });
    useMessage().createMessage.success('api.ts 生成成功');
  }
</script>
